const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const passport = require('passport');

const City = require('../../models/City');
const Country = require('../../models/Country');

router.get('/', (req, res) => {
	res.json([
		{
			title:'国家城市',
			api:'api/country/list',
			post:'get',
			return:{
				data:[
					{
						"city": [],
						"date": "2019-12-28T14:55:28.776Z",
						"_id": "5e076e02f1d591b841fc9c75",
						"country": "中国",
						"lanX": "1",
						"lanY": "2",
						"__v": 0
					}
				],
				status:2
			}
		},{
			title:'国家城市 新增',
			api:'api/country/add',
			post:'post',
			params:{
				country: '国家',
				lanX:'国家X坐标',
				lanY:'国家Y坐标',
				cityLanX:'国家X坐标',
				cityLanY:'国家Y坐标',
				city:'城市'
			},
			Header: '头部验证 Header：{Authorization:token字段}'
		},{
			title:'国家城市 删除',
			api:'api/country/delete/:id',
			params:'id可为城市id和国家id',
			post:'post',
			Header: '头部验证 Header：{Authorization:token字段}'
		}
	])
})

router.post('/add',passport.authenticate('jwt',{session:false}),(req,res)=>{
	let params={}
	let cityParams = {}
	if (req.body.country) params.country = req.body.country
	if (req.body.lanX) params.lanX = req.body.lanX
	if (req.body.lanY) params.lanY = req.body.lanY

	if (req.body.city) cityParams.city = req.body.city
	if (req.body.lanX) cityParams.lanX = req.body.cityLanX
	if (req.body.lanY) cityParams.lanY = req.body.cityLanY

	new City(cityParams).save().then(city => {
		params.city = city._id
		Country.findOne({country:params.country}).then(findCountry=>{
			if (findCountry){
				findCountry.city.unshift(city._id)
				Country.findOneAndUpdate(
					{_id:findCountry._id},
					{$set:{city:findCountry.city}},
					{new:true}
				).then(updata=>{
					res.json({
						data:updata,
						status:2
					})
				}).catch(e=>{
					City.findOneAndRemove({_id:city._id}).then(()=>{
						res.status(500).json({
							msg:'服务器错误',
							status:0
						})
					})
				})
			} else {
				new Country(params).save().then(country => {
					res.json({
						data:country,
						status:2
					})
				})
			}
		})
	})
})


router.delete('/delete/:id',passport.authenticate('jwt',{session:false}), (req,res)=>{
	/**
	 * 判断id是国家的id还是城市id，
	 * 1.城市id，删除城市数据库，更新国家数据库，
	 * 2.国家id，查询国家数据中是否有城市，有城市不让删除，没有可以删除
	 */

	City.findOne({_id:req.params.id}).then(city=>{
		if (city) {
			City.findOneAndRemove({_id:req.params.id}).then((data)=>{
				Country.findOne({ city: req.params.id }).then(data => {
					let newCity=data.city.filter(item => item !=req.params.id)
					Country.findOneAndUpdate({ city: req.params.id },{$set:{city:newCity}}, {new:true}).then(updata=>{
						return res.json({
							data:updata,
							status:2
						})
					})
				})
			})
		} else {
			Country.findOne({ _id: req.params.id }).then(data => {
				if(data.city.length>0){
					res.status(400).json({
						msg:'city中有数据，不能删除',
						status:0
					})
				} else {
					Country.findOneAndRemove({ _id: req.params.id }).then(remove=>{
						return res.json({
							data:remove,
							status:2
						})
					}).catch(e => {
						res.status(500).json({
							msg:'删除失败',
							status:0
						})
					})
				}
			}).catch(e => {
				res.status(500).json({
					msg:'服务器错误',
					status:0
				})
			})
		}
	}).catch(e=>{
		// 国家的id删除
		Country.findOne({ _id: req.params.id }).then(data => {
			if(data.city.length>0){
				res.status(400).json({
					msg:'city中有数据，不能删除',
					status:0
				})
			} else {
				Country.findOneAndRemove({ _id: req.params.id }).then(remove=>{
					return res.json({
						data:remove,
						status:2
					})
				}).catch(e => {
					res.status(500).json({
						msg:'删除失败',
						status:0
					})
				})
			}
		}).catch(e => {
			res.status(500).json({
				msg:'服务器错误',
				status:0
			})
		})
	})
} )

router.get('/list', (req,res)=>{
	Country.find().populate({path:'city'}).exec(function (err, data) {
		res.json({
			data,
			status:2
		})
	})
})




module.exports = router
